package com.lucky.auth_boot.exception;

import com.lucky.auth_boot.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AuthenticationException.class)
    public Result<?> authenticationException(AuthenticationException e) throws AuthenticationException {
        return Result.error(402, e.getMessage());
//        throw e;
    }

    /**
     * 自定义异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result<?> businessExceptionHandler(BusinessException e) {
        log.error("GlobalExceptionHandler businessExceptionHandler error message: {}", e.getMessage(), e);
        if(e.getCode() != null) {
            return Result.error(e.getCode(),e.getMessage());
        }
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Result<?> exceptionHandler(Exception e) throws Exception {
        if (e instanceof AccessDeniedException || e instanceof AuthenticationException) {
            throw e;
        }
        log.error("GlobalExceptionHandler exceptionHandler error message: {}", e.getMessage(), e);
        return Result.error("服务器内部错误，请联系管理员");
    }
}